import { useEffect, useState } from "react";
import style from "./index.module.scss";

import desc from "@/assets/images/halloween/bg-desc.png";
import song_s from "@/assets/images/halloween/song_s.png";
import song_d from "@/assets/images/halloween/song_d.png";
import shou_s from "@/assets/images/halloween/shou_s.png";
import shou_d from "@/assets/images/halloween/shou_d.png";
import zhao_s from "@/assets/images/halloween/zhao_s.png";
import zhao_d from "@/assets/images/halloween/zhao_d.png";

import Icon1 from "@/assets/images/halloween/1.png";
import Icon2 from "@/assets/images/halloween/2.png";
import Icon3 from "@/assets/images/halloween/3.png";

import { goUserPage, showToast } from "./util";

console.log(process.env.REACT_APP_ENV);
const BaseUrl =
  process.env.REACT_APP_ENV === "prod"
    ? "https://webapi.pupupal.com"
    : "https://kk-test-webapi.sayhaiapp.com";
const Content = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const authorizationToken = urlParams.get("userId");
  console.log("authorizationToken", authorizationToken);

  // 1送月饼 2收月饼 3找月饼
  const [type, setType] = useState(1);
  const [data, setData] = useState([]);
  const [info, setInfo] = useState(); // 当前用户信息
  const getRank = async () => {
    let url;
    switch (type) {
      case 1:
        url = `/gift/halloween/rank/send/candy/rank`;
        break;
      case 2:
        url = `/gift/halloween/rank/receive/candy/rank`;
        break;
      case 3:
        url = `/gift/halloween/rank/find/candy/rank`;
        break;
    }
    fetch(BaseUrl + url, {
      method: "GET",
      headers: {
        Authorization: authorizationToken,
      },
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.code === 200 && response.data) {
          setData(response.data.list || []);
          setInfo(response.data.myRank);
        } else {
          setData([]);
          console.error("Failed to fetch ranking data:", response.msg);
          showToast(response.msg);
        }
      })
      .catch((error) => console.error("Error fetching ranking data:", error));
  };

  const fetchSubscribe = async (item, url) => {
    fetch(BaseUrl + url, {
      method: "POST",
      headers: {
        Authorization: authorizationToken,
        "content-type": "application/json",
      },
      body: JSON.stringify({
        targetUserId: item.userId,
        userId: info.userId,
      }),
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.code === 200 && response.data) {
          console.log("成功");
          getRank();
        } else {
          console.error("Failed to fetch ranking data:", response.msg);
          showToast(response.msg);
        }
      })
      .catch((error) => console.error("Error fetching ranking data:", error));
  };

  const clickSubscribe = async (item) => {
    if (item.userId === info?.userId) {
      // 禁止关注自己
      return;
    }
    if (item.relation === 2 || item.relation === 3) {
      fetchSubscribe(item, `/user/friend/subscribe`); // 去关注
    } else if (item.relation === 1 || item.relation === 4) {
      fetchSubscribe(item, `/user/friend/unsubscribe`); // 取消关注
    }
  };

  useEffect(() => {
    if (authorizationToken) {
      getRank();
    } else {
      console.error("Authorization token not found in URL");
    }
  }, [type]);

  return (
    <>
      <div className={style.content_wrap}>
        <div className={style.descBox}>
          <img src={desc} alt="图" />
        </div>
        <div className={style.rank_container}>
          <div className={style.btn_box}>
            <div
              className={`${style.btn_switch}  ${
                type === 1 ? "" : style.no_select
              }`}
              onClick={() => setType(1)}
            >
              <img src={type === 1 ? song_s : song_d} alt="" />
            </div>
            <div
              className={`${style.btn_switch} ${
                type === 2 ? "" : style.no_select
              } `}
              onClick={() => setType(2)}
            >
              <img src={type === 2 ? shou_s : shou_d} alt="" />
            </div>
            <div
              className={`${style.btn_switch} ${
                type === 3 ? "" : style.no_select
              } `}
              onClick={() => setType(3)}
            >
              <img src={type === 3 ? zhao_s : zhao_d} alt="" />
            </div>
          </div>
          <div className={style.rank_box}>
            <div className={style.rank_list}>
              {data.map((item, i) => (
                <div className={style.td_box} key={item?.userId}>
                  {i === 0 && (
                    <div className={style.rank}>
                      <img src={Icon1} alt=""></img>
                      <span>1</span>
                    </div>
                  )}
                  {i === 1 && (
                    <div className={style.rank}>
                      <img src={Icon2} alt=""></img>
                      <span>2</span>
                    </div>
                  )}
                  {i === 2 && (
                    <div className={style.rank}>
                      <img src={Icon3} alt=""></img>
                      <span>3</span>
                    </div>
                  )}
                  {i > 2 && (
                    <div className={style.rank}>{i >= 99 ? "99+" : i + 1}</div>
                  )}
                  <div className={style.user}>
                    <img
                      src={item?.avatar}
                      alt=""
                      onClick={() => goUserPage(item.userId)}
                    />
                    <div>
                      <div className={style.nickname}>
                        {item.nickname || item.account}
                      </div>
                      <div className={style.score}>
                        {type === 3 ? "找糖果数" : "捣蛋值"}：{item?.showValue}
                      </div>
                    </div>
                  </div>
                  <div
                    className={
                      item.relation === 1 || item.relation === 4
                        ? style.rankBtn_blue
                        : style.rankBtn
                    }
                    onClick={() => clickSubscribe(item)}
                    style={{
                      opacity:
                        item.relation < 5 && item.userId !== info?.userId
                          ? 1
                          : 0.6,
                    }}
                  >
                    {item.relation === 1 && "已关注"}
                    {item.relation === 2 && "回关+"}
                    {item.relation === 3 && "关注+"}
                    {item.relation === 4 && "已互关"}
                    {item.relation === 5 && "关注+"}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className={`${style.user_box}`}>
            <div className={style.user_content}>
              <div className={style.left}>
                <div className={style.my_rank_desc}>我的排名</div>
                <div className={style.my_rank_index}>
                  {info?.rank || "未上榜"}
                </div>
              </div>
              <div className={style.user}>
                <img src={info?.avatar} alt="" />
                <span>{info?.nickname || info?.account || "我的昵称"}</span>
              </div>
              <div className={style.right}>
                <div className={style.my_rank_desc}>
                  {type === 3 ? "找糖果数" : "捣蛋值"}
                </div>
                <div className={style.my_rank_num}>{info?.showValue || 0}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Content;
